import cv2
import matplotlib.pyplot as plt


def read_video_and_plot_grayscale(video_path, x, y):
    # 打开视频文件
    cap = cv2.VideoCapture(video_path)

    # 检查是否成功打开视频
    if not cap.isOpened():
        print("Error: Could not open video.")
        return

    # 获取视频的总帧数
    total_frames = int(cap.get(cv2.CAP_PROP_FRAME_COUNT))
    print(f"Total frames: {total_frames}")

    # 存储灰度值的列表
    grayscale_values = []

    # 循环读取每一帧
    while True:
        ret, frame = cap.read()

        # 如果读取成功
        if ret:
            # 将帧转换为灰度图像
            gray_frame = cv2.cvtColor(frame, cv2.COLOR_BGR2GRAY)

            # 获取指定像素点的灰度值
            grayscale_value = gray_frame[y, x]
            grayscale_values.append(grayscale_value)
        else:
            break

    # 释放视频捕获对象
    cap.release()

    # 绘制灰度值波形图
    print(grayscale_values)
    plt.figure(figsize=(10, 5))
    plt.plot(grayscale_values, label=f'Grayscale value at ({x}, {y})')
    plt.xlabel('Frame')
    plt.ylabel('Grayscale Value')
    plt.title('Grayscale Value Over Time')
    plt.legend()
    plt.grid(True)
    plt.show()


# 使用示例
video_path = '20240516192320.mp4'
x, y = 2, 0  # 指定像素点位置
read_video_and_plot_grayscale(video_path, x, y)
